package org.hchdubbo.consumer;

import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URLDecoder;
import java.util.List;

/**
 * @Author: HeCongHui
 * @Time :2021/12/15 11:03
 */
public class RpcClientProxy {
    @Autowired
    private ServiceDiscover serviceDiscover;
    public <T> T create(Class<T> tClass) {
        return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String serviceName = tClass.getName();
                // 1. 根据服务名称 去zk上获取接口调用地址 mayiktrpc://127.0.0.1:8080
                List<String> discover = serviceDiscover.getDiscover(serviceName);
                //mayiktrpc://127.0.0.1:8080
                String addres = discover.get(0);
                RpcRequest rpcRequest = new RpcRequest(
                        serviceName, method.getName(), method.getParameterTypes(), args
                );
                // 2.拼接调用接口地址mayiktrpc://127.0.0.1:8080/com.mayikt.service.api.MemberService getgetUser(1)  tClass.getName
                // 3.使用nettyclient向netty服务器端发送消息
                String[] splitAddres = URLDecoder.decode(addres, "UTF-8").split(":");
                String host = splitAddres[1].replace("//","");
                String port = splitAddres[2];
                return sendMsg(host, Integer.parseInt(port), rpcRequest);
            }
        });
    }

}
